var urNavLevels = [];

dojo.addOnLoad(function() {
	if (urNavLevelsJson) {
		urNavLevels = JSON.parse(urNavLevelsJson);
	}
	// 添加当前报表名
	urNavLevels.push(reportName);
	
	var innerDivs = dojo.query('.innerDiv');
	for ( var i = 0; i < innerDivs.length; i++) {
		var tables = innerDivs[i].getElementsByTagName('table');
		if (tables.length) {
			var table = tables[0];
			var anchors = table.getElementsByTagName('a');
			if (anchors.length) {
				dojo.forEach(anchors, function(anchor) {
					var target = dojo.attr(anchor, 'target');
					var href = dojo.attr(anchor, 'href');
					if (target == '_self' || target == '_parent' || target == '_top') {
						// 目前只支持http协议，且必须包含指定action名称
						if (href.indexOf('/') == 0 || href.indexOf('http://') == 0 || 
								(href.indexOf('javascript:') != 0 && href.indexOf('#') != 0)) {
							if (href.indexOf('Report-Guage.'+window.action_suffix) >= 0) {
								href += "&ur_nav_levels=" + encodeto64(JSON.stringify(urNavLevels)).replace(/\+/g, '-').replace(/\//g, '_');
								dojo.attr(anchor, 'href', href);
							} else if (href.indexOf('Report-ResultAction.'+window.action_suffix) >= 0 || 
									href.indexOf('Report-EntryAction.'+window.action_suffix) >= 0) {
								// 添加';1'表示回退时退1步，默认为2步
								var l = urNavLevels.length;
								urNavLevels[l - 1] += ';1';
								href += "&ur_nav_levels=" + encodeto64(JSON.stringify(urNavLevels)).replace(/\+/g, '-').replace(/\//g, '_');
								dojo.attr(anchor, 'href', href);
								urNavLevels[l - 1] = urNavLevels[l - 1].substr(0, urNavLevels[l - 1].length - 2);
							}
						}
					}
				});
			}
		}
	}

	if (urNavLevels.length  > 1) {
		// 创建导航条
		var navigation = document.createElement('div');
		dojo.attr(navigation, 'id', 'navigation');
		dojo.addClass(navigation, 'report_navigation');
		var contentDiv = dojo.byId('resultForm');
		dojo.place(navigation, contentDiv, 'first');
		refreshNavigation();
	}
});

function refreshNavigation() {
	var navigation = dojo.byId('navigation');
	dojo.empty(navigation);
	var span = document.createElement('span');
	span.innerHTML = ' > ';
	dojo.place(span, navigation, 'last');
	for ( var i = 0; i < urNavLevels.length; i++) {
		span = document.createElement('span');
		if (urNavLevels[i].indexOf(';') > 0) {
			span.innerHTML = urNavLevels[i].substr(0, urNavLevels[i].indexOf(';'));
		} else {
			span.innerHTML = urNavLevels[i];
		}
		dojo.place(span, navigation, 'last');
		if (i != urNavLevels.length - 1) {
			dojo.addClass(span, 'link');
			span.onclick = dojo.hitch(null, "goToLevel", i);
			span = document.createElement('span');
			span.innerHTML = ' > ';
			dojo.place(span, navigation, 'last');
		}
	}
}

function goToLevel(levelNo) {
	// 使用history.go()实现
	var num = 0;
	for (var i = levelNo; i < urNavLevels.length - 1; i++) {
		var level = urNavLevels[i];
  		var add = getNavStepFromLevel(level).step;
		num += add;
	}
	history.go(-num);
}
